<template>
  <div class="tenant-container">
    <!-- 搜索表单 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="用户名：">
        <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
      </el-form-item>
      <el-form-item label="性别：">
        <el-select v-model="searchForm.gender" placeholder="请选择性别" clearable>
          <el-option label="男" value="male" />
          <el-option label="女" value="female" />
        </el-select>
      </el-form-item>
      <el-form-item label="房源ID：">
        <el-input v-model="searchForm.houseId" placeholder="请输入房源ID" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="operation-buttons">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>添加租户
      </el-button>
    </div>

    <!-- 已入住用户列表 -->
    <el-table
        :data="tenants"
        style="width: 100%"
        v-loading="loading"
        border
        stripe
        highlight-current-row
    >
      <el-table-column prop="username" label="用户名" width="120" />
      <el-table-column prop="gender" label="性别" width="80">
        <template #default="{ row }">
          <el-tag :type="row.gender === 'male' ? '' : 'danger'">
            {{ row.gender === 'male' ? '男' : '女' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" width="130" />
      <el-table-column prop="email" label="邮箱" width="180" />
      <el-table-column prop="houseId" label="房源ID" width="100" />
      <el-table-column prop="checkInDate" label="入住日期" width="120" />
      <el-table-column prop="leaseTerm" label="租期(月)" width="100" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 'active' ? 'success' : 'info'">
            {{ row.status === 'active' ? '在住' : '已退租' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="160" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button
              size="small"
              type="danger"
              @click="handleDelete(row.id)"
              :disabled="row.status === 'active'"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单
const searchForm = ref({
  username: '',
  gender: '',
  houseId: ''
})

// 分页数据
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)

// 模拟所有租户数据
const allTenants = ref([
  {
    id: '1',
    username: '张三',
    gender: 'male',
    phone: '13800138001',
    email: 'zhangsan@example.com',
    houseId: 'H001',
    checkInDate: '2023-01-15',
    leaseTerm: 12,
    status: 'active',
    createTime: '2023-01-10'
  },
  {
    id: '2',
    username: '李四',
    gender: 'male',
    phone: '13800138002',
    email: 'lisi@example.com',
    houseId: 'H002',
    checkInDate: '2023-02-20',
    leaseTerm: 6,
    status: 'active',
    createTime: '2023-02-18'
  },
  {
    id: '3',
    username: '王五',
    gender: 'female',
    phone: '13800138003',
    email: 'wangwu@example.com',
    houseId: 'H003',
    checkInDate: '2023-03-10',
    leaseTerm: 12,
    status: 'active',
    createTime: '2023-03-08'
  },
  {
    id: '4',
    username: '赵六',
    gender: 'male',
    phone: '13800138004',
    email: 'zhaoliu@example.com',
    houseId: 'H004',
    checkInDate: '2023-04-05',
    leaseTerm: 18,
    status: 'active',
    createTime: '2023-04-01'
  },
  {
    id: '5',
    username: '孙七',
    gender: 'female',
    phone: '13800138005',
    email: 'sunqi@example.com',
    houseId: 'H005',
    checkInDate: '2023-05-20',
    leaseTerm: 12,
    status: 'active',
    createTime: '2023-05-18'
  },
  {
    id: '6',
    username: '周八',
    gender: 'male',
    phone: '13800138006',
    email: 'zhouba@example.com',
    houseId: 'H006',
    checkInDate: '2023-01-05',
    leaseTerm: 6,
    status: 'inactive',
    createTime: '2023-01-01'
  },
  {
    id: '7',
    username: '吴九',
    gender: 'female',
    phone: '13800138007',
    email: 'wujiu@example.com',
    houseId: 'H007',
    checkInDate: '2023-02-10',
    leaseTerm: 12,
    status: 'inactive',
    createTime: '2023-02-08'
  },
  {
    id: '8',
    username: '郑十',
    gender: 'male',
    phone: '13800138008',
    email: 'zhengshi@example.com',
    houseId: 'H008',
    checkInDate: '2023-03-15',
    leaseTerm: 6,
    status: 'inactive',
    createTime: '2023-03-12'
  },
  {
    id: '9',
    username: '钱十一',
    gender: 'female',
    phone: '13800138009',
    email: 'qian11@example.com',
    houseId: 'H009',
    checkInDate: '2023-04-20',
    leaseTerm: 12,
    status: 'inactive',
    createTime: '2023-04-18'
  },
  {
    id: '10',
    username: '孙十二',
    gender: 'male',
    phone: '13800138010',
    email: 'sun12@example.com',
    houseId: 'H010',
    checkInDate: '2023-05-25',
    leaseTerm: 6,
    status: 'inactive',
    createTime: '2023-05-22'
  }
])

// 表格数据（计算属性，根据搜索条件过滤）
const tenants = computed(() => {
  let filtered = allTenants.value

  // 应用搜索过滤
  if (searchForm.value.username) {
    filtered = filtered.filter(item =>
        item.username.includes(searchForm.value.username)
    )
  }

  if (searchForm.value.gender) {
    filtered = filtered.filter(item =>
        item.gender === searchForm.value.gender
    )
  }

  if (searchForm.value.houseId) {
    filtered = filtered.filter(item =>
        item.houseId.includes(searchForm.value.houseId)
    )
  }

  // 更新总数
  total.value = filtered.length

  // 应用分页
  const startIndex = (pageNum.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  return filtered.slice(startIndex, endIndex)
})

// 获取数据
const fetchTenants = () => {
  loading.value = true

  // 模拟API请求延迟
  setTimeout(() => {
    // 数据已通过计算属性自动处理
    loading.value = false
  }, 500)
}

// 搜索
const handleSearch = () => {
  pageNum.value = 1
  fetchTenants()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    username: '',
    gender: '',
    houseId: ''
  }
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchTenants()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  pageNum.value = val
  fetchTenants()
}

// 添加租户
const handleAdd = () => {
  ElMessage.info('添加租户功能已触发，实际项目中会打开添加对话框')
}

// 编辑租户
const handleEdit = (row: any) => {
  ElMessage.info(`编辑租户: ${row.username}，实际项目中会打开编辑对话框`)
}

// 删除租户
const handleDelete = (id: string) => {
  ElMessageBox.confirm('确定要删除该租户吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 从数组中删除
    allTenants.value = allTenants.value.filter(item => item.id !== id)

    // 如果删除后当前页没有数据了，跳转到上一页
    if (tenants.value.length === 0 && pageNum.value > 1) {
      pageNum.value--
    }

    ElMessage.success('删除成功')
    fetchTenants()
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 初始化加载数据
onMounted(() => {
  fetchTenants()
})
</script>

<style scoped lang="scss">
.tenant-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  margin-bottom: 20px;
  :deep(.el-form-item) {
    margin-right: 15px;
    margin-bottom: 0;
  }
}

.operation-buttons {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin-top: 20px;
}
</style>